package com.boyu.backend;

import com.boyu.common.BaseController;
import com.boyu.common.SystemConst;
import com.boyu.common.model.Option;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * _OptionController
 */
public class _OptionController extends BaseController {

	public void index() {
		String groupId = getPara("groupId");
		String sql = "select * from t_option";
		if (groupId != null) {
			sql += " where groupId=" + groupId;
		}
		final List<Option> options = Option.dao.find(sql);
		setAttr("optionList", options);
		render(INDEX_HTML);
	}

	public void add() {
		render(ADD_HTML);
	}

	public void edit() {
		long id = getParaToLong(ID);
		Option byId = Option.dao.findById(id);
		setAttr("model", byId);
		render(EDIT_HTML);
	}

	public void save() {
		Option model = getModel(Option.class, "");
		if (model.getId() != null) {
			model.update();
		} else {
			model.save();
		}
		redirect(INDEX);
	}

	public void del() {
		Option.dao.deleteById(getParId());
		redirect(INDEX);
	}

	public void toUploadImage() {
		String webRootPath = PathKit.getWebRootPath();
		String dic = webRootPath + File.separator + "upload" + File.separator + "sys";
		IOFileFilter txt = FileFilterUtils.or(FileFilterUtils.suffixFileFilter("jpg"),FileFilterUtils.suffixFileFilter("png"));
		IOFileFilter instance = DirectoryFileFilter.INSTANCE;
		Collection collection = FileUtils.listFiles(new File(dic), txt, instance);

		List<String> fileNameList = new ArrayList<>();
		for (Object o : collection) {
			fileNameList.add(((File) o).getName());
		}
		setAttr("fileNameList",fileNameList);
		render("uploadImage.html");
	}

	public void uploadImage() {
		UploadFile fileName = getFile("fileName", SystemConst.UPLOAD_SYSTEM);
		render("uploadImage.html");
	}
}





